package com.demo.common.support.builder;

import com.demo.common.support.model.DataResponse;
import com.demo.common.support.page.Page;
import com.demo.common.support.page.PageResponse;
import com.demo.common.support.page.Pageable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.Collection;
import java.util.Objects;

/**
 * 交互数据实体构建器
 *
 * @author molong
 * @since 2024/5/24
 */
public class ResponseBuilder<T> extends BaseResponseBuilder<T>{
    private Pageable pageable;

    private long total;

    private int currPage;

    private int pageSize;

    /**
     * 实例化一个构建器
     *
     * @param <T> 数据类型
     * @return 构建器
     */
    public static <T> ResponseBuilder<T> start() {
        return new ResponseBuilder<>();
    }

    @Override
    public DataResponse<T> build() {
        if (Objects.nonNull(pageable)) {
            this.currPage = pageable.getCurrPage();
            this.pageSize = pageable.getPageSize();
        }
        if (this.currPage > 0 && this.pageSize > 0) {
            PageResponse<T> pageResponse = new PageResponse<>();
            pageResponse.setPage(new Page(this.total, this.currPage, this.pageSize));
            pageResponse.setData(datas);
            pageResponse.setCode(this.code);
            pageResponse.setMessage(this.message);
            if (!ObjectUtils.isEmpty(extend)) {
                pageResponse.setExtend(extend);
            }
            return pageResponse;
        }
        return super.build();
    }


    /**
     * 设置数据总条数
     *
     * @param total 数据总条数
     * @return 分页构建器
     */
    public ResponseBuilder<T> total(long total) {
        Assert.state(total >= 0, "Total number should be a natural number!");
        this.total = total;
        return this;
    }

    /**
     * 设置当前页
     *
     * @param currPage 当前端
     * @return 分页构建器
     */
    public ResponseBuilder<T> currPage(int currPage) {
        this.currPage = currPage;
        return this;
    }

    /**
     * 设置分页大小
     *
     * @param pageSize 分页大小
     * @return 分页构建器
     */
    public ResponseBuilder<T> pageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }


    public ResponseBuilder<T> page(Pageable pageable) {
        this.pageable = pageable;
        return this;
    }

    public ResponseBuilder<T> page(Pageable pageable, long total) {
        this.pageable = pageable;
        this.total = total;
        return this;
    }

    public ResponseBuilder<T> page(Pageable pageable, long total, Collection<T> datas) {
        this.pageable = pageable;
        this.total = total;
        this.datas = datas;
        return this;
    }

    @Override
    public ResponseBuilder<T> data(Collection<T> datas) {
        this.datas = datas;
        return this;
    }
}

